/* Blink Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "lvgl_init.h"
#include "freertos/semphr.h"
/* Can use project configuration menu (idf.py menuconfig) to choose the GPIO to blink,
   or you can edit the following line and set a number here.
*/
#define BLINK_GPIO CONFIG_BLINK_GPIO
#define SEMA_COUNT_MAX_NUMBERS 10 //SEMA_COUNT 信号量队列最大长度10
#define SEMA_COUNT_INIT_NUMBERS 10//SEMA_COUNT 信号量初始值10

int count = SEMA_COUNT_INIT_NUMBERS;//count计数大小等于SEMA_COUNT_INIT_NUMBERS
char buffer[50];//显示内容缓冲区
SemaphoreHandle_t Seam_Count;//计数信号量句柄
extern SemaphoreHandle_t LVGL_Started;//二值信号量句柄
extern lv_obj_t * label_1;//标签句柄

void Create_Sema_count()//创建计数信号量
{
    Seam_Count=xSemaphoreCreateCounting(SEMA_COUNT_MAX_NUMBERS,SEMA_COUNT_INIT_NUMBERS);
}

void Take_Sema_count()//获取计数信号量线程
{
    while(LVGL_Started == NULL)//检测信号量是否创建
    {
        vTaskDelay(1000/portTICK_PERIOD_MS);//释放线程
        printf("thread is not working");//输出线程不在运行
    }
    xSemaphoreTake(LVGL_Started,portMAX_DELAY);//信号量已创建，获取信号量。

    while (1)
    {
        if(Seam_Count != NULL)//检测信号量是否创建
        {
            xSemaphoreTake(Seam_Count,portMAX_DELAY);//获取计数信号量
            sprintf(buffer,"Seam has taken num is #0fff00 %d#",count--);//计数值减去1.刷新显示数字
            lv_label_set_text(label_1,buffer);//刷新文本内容
        }
        vTaskDelay(1000 / portTICK_PERIOD_MS);//释放线程1s
    }
}
void app_main(void)
{
    /* Configure the IOMUX register for pad BLINK_GPIO (some pads are
       muxed to GPIO on reset already, but some default to other
       functions and need to be switched to GPIO. Consult the
       Technical Reference for a list of pads and their default
       functions.)
    */
    Create_Sema_count();//创建计数信号量

    xTaskCreatePinnedToCore(guiTask, "gui", 1024*2, NULL, 11, NULL, 1);//创建GUI初始化线程

    xTaskCreatePinnedToCore(Take_Sema_count, "Seam_Count", 1024*2, NULL, 10, NULL, 1);//创建Seam_Count线程，定期获取计数信号量

    /*闪灯部分，提示系统运行*/
    gpio_reset_pin(BLINK_GPIO);
    /* Set the GPIO as a push/pull output */
    gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
    while(1)
    {
        /* Blink off (output low) */
        printf("Turning off the LED\n");
        gpio_set_level(BLINK_GPIO, 0);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        /* Blink on (output high) */
        printf("Turning on the LED\n");
        gpio_set_level(BLINK_GPIO, 1);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}
